﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Threading;
using NAudio.CoreAudioApi;
using System.Collections.ObjectModel;
using NAudio.Wave;

namespace SoundLeech
{
    public partial class Form1 : Form
    {
        IWaveIn waveIn=null;
        WaveFileWriter writer;
        
        public Form1()
        {
            InitializeComponent();
           // Convert2Mp3.ConvertWav2Mp3("Spotify - Mezzoforte – Beyond The Horizon");
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();
            MMDeviceCollection deviceCol = deviceEnum.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);

            Collection<MMDevice> devices = new Collection<MMDevice>();
            Process processById = Process.GetProcessesByName("spotify")[0];
            if (processById.MainWindowTitle.ToLower().Contains("spotify"))
            {
                foreach (MMDevice device in deviceCol)
                {
                    if (device.FriendlyName.ToLower() == "speakers")
                        waveIn = new WasapiLoopbackCapture(device);
                }
                if (waveIn == null)
                {
                    MessageBox.Show("Unable to tap speaker output");
                    throw new Exception();
                }
                waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
                waveIn.RecordingStopped += new EventHandler(waveIn_RecordingStopped);
                waveIn.StartRecording();

                Thread mt = new Thread(monitorWindowTitle);

                string mainWindowTitle = processById.MainWindowTitle;
                mt.Start(new object[] { processById.Id, mainWindowTitle });

            }
            else
            {
                MessageBox.Show("Spotify not detected");
                throw new Exception();
            }
        }

        void waveIn_RecordingStopped(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler(waveIn_RecordingStopped), sender, e);
            }
            else
            {
                waveIn.Dispose();
                waveIn = null;
                writer.Close();
                writer = null;
                //buttonStartRecording.Enabled = true;
                //progressBar1.Value = 0;
                
            }
        }

        void waveIn_DataAvailable(object sender, WaveInEventArgs e)
        {
            if (this.InvokeRequired)
            {
                //Debug.WriteLine("Data Available");
                this.BeginInvoke(new EventHandler<WaveInEventArgs>(waveIn_DataAvailable), sender, e);
            }
            else
            {
                if (writer != null)
                {
                    int s = 0;
                    for (int i = 0; i < 100; i++) s += e.Buffer[i];
                    if (s >0)
                    lock (writer)
                    {
                        if (writer != null)
                           writer.Write(e.Buffer, 0, e.BytesRecorded);
                    }
                }
                //Debug.WriteLine("Flushing Data Available");
                //writer.Write(e.Buffer, 0, e.BytesRecorded);                
            }
        }
        delegate void SetTextCallback(string text);
        void SetText(string text)
        {
            lblStatus.Text = text;
        }

     
        public  void monitorWindowTitle(object data)
        {
            string mwt = ((object[])data)[1] as string;
            int processID = (int)((object[])data)[0];

            while (true)
            {
                Process processById = Process.GetProcessById(processID);
                string mainWindowTitle = processById.MainWindowTitle;
                if (mainWindowTitle != mwt && mwt != "Spotify")
                {
                    if (writer != null)
                    {
                        lock (writer)
                        {
                            writer.Close();
                            writer = null;
                            //Debug.WriteLine("Closing song file, new song detected");
                            Thread convertSong = new Thread(Convert2Mp3.ConvertWav2Mp3);
                            convertSong.Start(new object[] { processedFiles, mwt.Replace("Spotify - ", ""), this });
                        }
                    }
                    //return;
                }
                 if (writer == null && mainWindowTitle != mwt) // Spotify starts playing. Get name of file.
                {
                    //Debug.WriteLine("New song started :" + mainWindowTitle);
                    string t = mainWindowTitle.Replace("Spotify - ", "");
                    writer = new WaveFileWriter(t+".wav", waveIn.WaveFormat);
                    SetTextCallback d = new SetTextCallback(SetText);
                    this.Invoke(d, new object[] { t });
                    mwt = mainWindowTitle;
                   
                }
            }
        }

    }
}
